package com.szx.java.listener;

import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import com.szx.java.handler.MyWebSocketHandler;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

/**
 * 上载进度侦听器
 * @author songzx
 * @create 2023-06-09 8:50
 */
public class UploadProgressListener implements ProgressListener {
    private long bytesWritten = 0;
    private long totalBytes;
    private boolean succeed = false;
    // 添加WebSocket实时告诉前端上传进度
    WebSocketSession session = null;

    public UploadProgressListener(long totalBytes) {
        this.totalBytes = totalBytes;
        this.session = MyWebSocketHandler.getSession();
    }

    @Override
    public void progressChanged(ProgressEvent progressEvent) {
        long bytes = progressEvent.getBytes();
        ProgressEventType eventType = progressEvent.getEventType();

        switch (eventType) {
            case REQUEST_BYTE_TRANSFER_EVENT:
                this.bytesWritten += bytes;
                int percent = (int) (this.bytesWritten * 100.0 / this.totalBytes);
                if (session != null && session.isOpen()) {
                    try {
                        // 实时返回上传进度
                        session.sendMessage(new TextMessage( percent + "%"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case TRANSFER_COMPLETED_EVENT:
                try {
                    this.succeed = true;
                    this.session.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case TRANSFER_FAILED_EVENT:
                try {
                    this.succeed = false;
                    this.session.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    public boolean isSucceed() {
        return succeed;
    }
}
